<template>
  <div> 
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="序号" />
      <el-table-column prop="account" label="账号" />
      <el-table-column prop="userGroup" label="用户" />
      <el-table-column label="创建时间" prop="ctime" :formatter="formatTime" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="editbtn(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        v-model:current-page="formdata.currentPage"
        v-model:page-size="formdata.pageSize"
        :page-sizes="[5, 10, 20, 30]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="sizeChange"
        @current-change="currentPage"
      />
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { accountList, delAccount } from '@/api/account';
import dayjs from 'dayjs';
import { ElMessage } from 'element-plus';

const tableData = ref([]);
const total = ref(0);
const formdata = ref({
  currentPage: 1,
  pageSize: 10
});

// 弹窗显示隐藏
const showEdit = ref(true);

// 进入页面瞬间，请求第一页数据
const getList = async () => {
  try {
    const res = await accountList(formdata.value);
    tableData.value = res.data || [];
    total.value = res.total || 0;
    console.log(res);
  } catch (error) {
    console.error('获取数据失败', error);
    ElMessage.error('获取数据失败');
  }
};

getList();

// 当前页发生改变，重新请求接口
const currentPage = () => {
  getList();
};

// 每页数据长度发生改变，重新请求接口
const sizeChange = () => {
  getList();
};

// dayjs 日期转换
const formatTime = (row, column, cellValue) => {
  return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss');
};

// 删除用户
const del = async(id) => {
  console.log(id);
  let res = await delAccount({id});
  console.log(res);
  if (res.code == 0) {
    ElMessage.success('删除成功');
    getList();
  } else {
    ElMessage.error('删除失败');
  }
  
};
</script>

<style scoped lang="scss">
.page {
  margin-top: 30px;
}
</style>